var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'money/income/temp_list';
var _height = $(parent).height()-243,_width = $(parent).width()-2;

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'income'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#ic_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#ic_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#ic_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	doQueryBank : function(){
		commonDia = $.dialog({
			title : '选择银行账户',
			content : 'url:'+config.BASEPATH+'money/bank/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#ic_ba_code").val(selected.ba_code);
				$("#ba_name").val(selected.ba_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#ic_ba_code").val(selected.ba_code);
					$("#ba_name").val(selected.ba_name);
				}
			},
			cancel:true
		});
	},
	doQueryProperty : function(){
		commonDia = $.dialog({
			title : '选择费用类型',
			content : 'url:'+config.BASEPATH+'money/property/to_list_dialog/1',
			data : {multiselect:true},
			width : 350,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var temps = [];
				for(var i=0;i<selected.length;i++){
					var temp = {};
					temp.icl_mp_code = selected[i].pp_code;
					temp.icl_money = 0;
					temps.push(temp);
				}
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'money/income/temp_save',
					data:{"temps":JSON.stringify(temps)},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '保存成功'});
							THISPAGE.reloadGridData();
							commonDia.close();
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
				return false;
			},
			close:function(){
				
			},
			cancel:true
		});
	}
};

var handle = {
	temp_updateRemark:function(rowid,remark){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/income/temp_updateRemark',
			data:{icl_id:rowid,icl_remark:Public.encodeURI(remark)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	temp_updateMoney:function(rowid,money){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/income/temp_updateMoney',
			data:{icl_id:rowid,icl_money:money},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	temp_del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'money/income/temp_del',
					data:{"icl_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
							THISPAGE.gridTotal();
							var ids = $("#grid").getDataIDs();
							if(ids.length == 0){
								THISPAGE.addEmptyData();
							}
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    temp_clear:function(){
    	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'money/income/temp_clear',
				data:{},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$("#grid").clearGridData();
						THISPAGE.gridTotal();
						THISPAGE.addEmptyData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});
    },
	save:function(){
		if (!$("#form1").valid()) {
			return;
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		if (ids.length == 0){
			Public.tips({type: 2, content : '单据明细不存在，请选择收入类型！'});
			return;
		}
		$("#btn-save").attr("disabled",true);
		var saveUrl = config.BASEPATH+"money/income/save";
		if($("#ic_id").val() != undefined){
			saveUrl = config.BASEPATH+"money/income/update";
		}
		$.ajax({
			type:"POST",
			url:saveUrl,
			data:$('#form1').serialize(),
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.ic_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="新增">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		$("#ic_date").val(config.TODAY);
		this.selectRow={};
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var icl_money=grid.getCol('icl_money',false,'sum');
    	grid.footerData('set',{icl_pp_code:'合计：',icl_money:icl_money.toFixed(2)});
    	$("#ic_money").val(icl_money.toFixed(2));
    },
    addEmptyData:function(){
    	var emptyData = {icl_pp_code:'',pp_name:'',icl_money:'',icl_remark:''};
    	$("#grid").addRowData(0, emptyData);
    },
	initGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
	    	{label:'编号',name: 'icl_mp_code', index: 'icl_mp_code', width: 100},
	    	{label:'费用名称',name: 'mp_name', index: 'mp_name', width: 100},
	    	{label:'金额',name: 'icl_money', index: 'icl_money', width: 80,align:'right',sorttype: 'float',editable:true},
	    	{label:'备注',name: 'icl_remark', index: 'icl_remark', width: 180,editable:true}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'icl_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				var ids = $("#grid").getDataIDs();
				if(ids.length == 0){
					THISPAGE.addEmptyData();
				}
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				handle.temp_update(rowid, '0');
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(rowid == 0){
					return self.selectRow.value;
				}
				if(cellname == 'icl_money'  && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseFloat(value) == 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || parseFloat(value) >1e+11){
						return self.selectRow.value;
					}
					handle.temp_updateMoney(rowid, parseFloat(value).toFixed(2));
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'icl_remark' && self.selectRow.value != value){
					handle.temp_updateRemark(rowid, value);
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				if (cellname == 'icl_money' && self.selectRow.value != value){
					THISPAGE.gridTotal();
				}
				
			}
	    });
	},
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		//清除
        $('#btnClear').click(function(e){
        	e.preventDefault();
        	handle.temp_clear();
		});
        $('#grid').on('click', '.operating .ui-icon-plus', function (e) {
        	e.preventDefault();
        	Utils.doQueryProperty();
        });
        
        //删除-列表模式
		$('#grid').on('click', '.operating .ui-icon-trash', function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.temp_del(id);
		});
	}
};

THISPAGE.init();